package com.find.memories;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.find.memories.adapter.TabsAdapter;
import com.find.memories.service.MapService;
import com.find.memories.util.LogUtil;
import com.find.memories.util.Utils;

public class MainActivity extends FragmentActivity implements ActionBar.OnNavigationListener, OnClickListener {

    private String[] strYearItems = getYearItems();;
    private int selectedYearNo = -1;
    
    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;
    private LinearLayout llDays;
    private HorizontalScrollView mScrollView;
    private boolean fired = false;

    private TextView tvYear;
    private TextView[] mMenuTabs = new TextView[TabsAdapter.TAB_ORDER_MAX];
    private TextView[] mMonthTabs = new TextView[12];
    
    private TextView tvSelectMonth;
        
    private int mYear;
    private int mMonth;
    private int mDay;
    private int galleryDay;
    private int smsDay;
    private int mapDay;
    private int memoDay;
    
    
    protected boolean mIsAppExit = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_main);
        
        setView(savedInstanceState);

        setLayout();
        
        setEvent();
        
        setDate();
        
        boolean isRunService = Utils.checkRunningService(this, getPackageName() + ".service.MapService");
        if ( ! isRunService ) {
            LogUtil.d("start Service");
            startService(new Intent(this, MapService.class));
        }
    }
    
    private void setView(Bundle savedInstanceState) {
        mViewPager = (ViewPager)findViewById(R.id.pager);
        
        mTabsAdapter = new TabsAdapter(this, getSupportFragmentManager(), mViewPager);
        
        mViewPager.setOffscreenPageLimit(TabsAdapter.TAB_ORDER_MAX-1);
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
              LogUtil.d("arg0:"+arg0);
                for(int i=0;i<mMenuTabs.length;i++){
                    if(i == arg0){
                        mMenuTabs[i].setSelected(true);
                    }else{
                        mMenuTabs[i].setSelected(false);
                    }                
                }
                
                Fragment currentFragment = mTabsAdapter.getItem(arg0);
                setExistDay(((BaseFragment) currentFragment).getExistDays(getYear(), getMonth()));
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
//                LogUtil.d("arg0:"+arg0);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                
                if (state == ViewPager.SCROLL_STATE_IDLE){
                    int pos = mViewPager.getCurrentItem();
                    LogUtil.d("state:"+state+", mPager.getCurrentItem():"+pos);
//                    showCloudtab(pos, mCloudTabVisible[pos]);
                }
            }

        });
        
    }
    
    private void setLayout() {
        mMenuTabs[TabsAdapter.TAB_ORDER_GALLERY] = (TextView) findViewById(R.id.tab_gallery);
        mMenuTabs[TabsAdapter.TAB_ORDER_SMS] = (TextView) findViewById(R.id.tab_sms);
        mMenuTabs[TabsAdapter.TAB_ORDER_MAP] = (TextView) findViewById(R.id.tab_map);
        mMenuTabs[TabsAdapter.TAB_ORDER_MEMO] = (TextView) findViewById(R.id.tab_memo);
        
        selectedTabButton(mMenuTabs[TabsAdapter.TAB_ORDER_GALLERY]);
        
        tvYear = (TextView) findViewById(R.id.tvYear);
        tvYear.setOnClickListener(this);
        
        mMonthTabs[0] = (TextView) findViewById(R.id.tvMonth01);
        mMonthTabs[1] = (TextView) findViewById(R.id.tvMonth02);
        mMonthTabs[2] = (TextView) findViewById(R.id.tvMonth03);
        mMonthTabs[3] = (TextView) findViewById(R.id.tvMonth04);
        mMonthTabs[4] = (TextView) findViewById(R.id.tvMonth05);
        mMonthTabs[5] = (TextView) findViewById(R.id.tvMonth06);
        mMonthTabs[6] = (TextView) findViewById(R.id.tvMonth07);
        mMonthTabs[7] = (TextView) findViewById(R.id.tvMonth08);
        mMonthTabs[8] = (TextView) findViewById(R.id.tvMonth09);
        mMonthTabs[9] = (TextView) findViewById(R.id.tvMonth10);
        mMonthTabs[10] = (TextView) findViewById(R.id.tvMonth11);
        mMonthTabs[11] = (TextView) findViewById(R.id.tvMonth12);
        
        llDays = (LinearLayout)findViewById(R.id.llDays);
        mScrollView = (HorizontalScrollView) findViewById(R.id.hScrollView);
        tvSelectMonth = (TextView) findViewById(R.id.tvSelectMonth);
    }

    private String[] getYearItems() {
        String[] items = new String[100];
        
        for (int i=2000; i<2100; i++) {
            items[i-2000] = i + "";
        }
        
        return items;
    }
    
    private void setEvent() {
        for(int i=0;i<mMenuTabs.length;i++){
            mMenuTabs[i].setOnClickListener(this);
        }
        
        for(int i=0;i<mMonthTabs.length;i++){
            mMonthTabs[i].setOnClickListener(this);
            mMonthTabs[i].setTag(i+1);
        }
        
    }
    
    private void setDate() {
        Calendar c = Calendar.getInstance();
        int nYear = c.get(Calendar.YEAR);
        int nMonth = c.get(Calendar.MONTH);
        int nDay = c.get(Calendar.DAY_OF_MONTH);
        
        for (TextView tv : mMonthTabs) {
            tv.setBackgroundColor(Color.WHITE);
        }
        
//        mMonthTabs[nMonth].setBackgroundColor(Color.DKGRAY);
        
        setYear(nYear);
//        setMonth(nMonth+1);
//        tvDate.setText(getDateFromCalender(nYear, nMonth, nDay));
        
        selectedYearNo = Utils.getIndex(strYearItems, String.valueOf(nYear));
        
    }
    
    public String getTextViewDate() {
        return "";
    }
    
    private String getDateFromCalender(int nYear, int nMonth, int nDay) {
        nMonth += 1;
        
        String sMonth = String.valueOf(nMonth);
        if (nMonth < 10) sMonth = "0" + sMonth;
        
        String sDay = String.valueOf(nDay);
        if (nDay < 10) sDay = "0" + sDay;
            
        return String.format("%s.%s.%s", nYear, sMonth, sDay);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        return false;
    }


    public int[] getDate() {
//        String strDate = tvDate.getText().toString();
//        String[] arrayDate = strDate.split("\\.");
//        
//        int nYear = Integer.valueOf(arrayDate[0]);
//        int nMonth = Integer.valueOf(arrayDate[1]);
//        int nDay = Integer.valueOf(arrayDate[2]);
        
//        return new int[]{nYear, nMonth, nDay};
        return new int[]{2014, 8, 23};
    }
    
    public int getDaysCount() {
        return llDays.getChildCount();
    }

    public void setYear(int year) {
        mYear = year;
    }
    
    public int getYear() {
        return mYear;
    }
    
    public void setMonth(int month) {
        mMonth = month;
        
        tvSelectMonth.setVisibility(View.GONE);
    }
    
    public int getMonth() {
        return mMonth;
    }
    
    public void setDay(int day) {
        mDay = day;
        
        if (day == 0) {
            setGalleryDay(day);
            setSmsDay(day);
            setMapDay(day);
            setMemoDay(day);
            return;
        }
        
        switch (mViewPager.getCurrentItem()) {
            case TabsAdapter.TAB_ORDER_GALLERY:
                setGalleryDay(day);
                break;
            case TabsAdapter.TAB_ORDER_SMS:
                setSmsDay(day);
                break;
            case TabsAdapter.TAB_ORDER_MAP:
                setMapDay(day);
                break;
            case TabsAdapter.TAB_ORDER_MEMO:
                setMemoDay(day);
                break;
        }
    }
    
    public int getDay() {
        return mDay;
    }
    
    public int getGalleryDay() {
        return galleryDay;
    }

    public void setGalleryDay(int galleryDay) {
        this.galleryDay = galleryDay;
    }

    public int getSmsDay() {
        return smsDay;
    }

    public void setSmsDay(int smsDay) {
        this.smsDay = smsDay;
    }

    public int getMapDay() {
        return mapDay;
    }

    public void setMapDay(int mapDay) {
        this.mapDay = mapDay;
    }

    public int getMemoDay() {
        return memoDay;
    }

    public void setMemoDay(int memoDay) {
        this.memoDay = memoDay;
    }

    public void setExistDay(ArrayList<Integer> arrDays) {
        
        if (arrDays == null)
            return;
        
        llDays.removeAllViews();
        
        if (arrDays.contains(getDay())) {
            setDay(getDay());
        }
        
        TextView tvtv = null;
        for (Integer day : arrDays) {
            TextView tv = new TextView(this);
            tv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i=0; i<llDays.getChildCount(); i++) {
                        View view = llDays.getChildAt(i);
                        view.setBackgroundColor(Color.DKGRAY);
                    }
                    
                    String strDay = ((TextView)v).getText().toString();
                    setDay(Integer.valueOf(strDay));
                    v.setBackgroundColor(Color.BLUE);
                    
                    for (int i=0; i<mTabsAdapter.getCount(); i++) {
                        ((BaseFragment)mTabsAdapter.getItem(i)).onRefresh(getYear(), getMonth(), getDay());
                    }
                    
//                    Fragment currentFragment = mTabsAdapter.getItem(mViewPager.getCurrentItem());
//                    ((BaseFragment) currentFragment).onRefresh(getYear(), getMonth(), getDay());
                }
            });
            
            float width = getResources().getDimension(R.dimen.common_90px);
            tv.setLayoutParams(new LayoutParams((int) width, LayoutParams.MATCH_PARENT));
            tv.setGravity(Gravity.CENTER);
            
            tv.setBackgroundColor(Color.DKGRAY);
            
            if (getDay() == day) {
                tv.setBackgroundColor(Color.BLUE);
                tvtv = tv;
            } else {
                int rememberDay = 0;
                
                switch (mViewPager.getCurrentItem()) {
                    case TabsAdapter.TAB_ORDER_GALLERY:
                        rememberDay = getGalleryDay();
                        break;
                    case TabsAdapter.TAB_ORDER_SMS:
                        rememberDay = getSmsDay();
                        break;
                    case TabsAdapter.TAB_ORDER_MAP:
                        rememberDay = getMapDay();
                        break;
                    case TabsAdapter.TAB_ORDER_MEMO:
                        rememberDay = getMemoDay();
                        break;
                }
                
                if (rememberDay == day)
                    tv.setBackgroundColor(Color.BLUE);
            }
            
            tv.setTextSize(16);
            
            tv.setText(""+day);
            llDays.addView(tv);
        }
        
        if (tvtv != null) {
            mScrollView.setTag(tvtv);
            mScrollView.post(new Runnable() {
                @Override
                public void run() {
                    View v = (View) mScrollView.getTag();
                    if (Utils.getDeviceWidth(MainActivity.this) <= (int)v.getX())
                        mScrollView.scrollTo((int)v.getX(), 0);
                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvYear:
                showSelectYearDialog();
                break;
            case R.id.tvMonth01:
            case R.id.tvMonth02:
            case R.id.tvMonth03:
            case R.id.tvMonth04:
            case R.id.tvMonth05:
            case R.id.tvMonth06:
            case R.id.tvMonth07:
            case R.id.tvMonth08:
            case R.id.tvMonth09:
            case R.id.tvMonth10:
            case R.id.tvMonth11:
            case R.id.tvMonth12:
                
//                if (getMonth() == (Integer)view.getTag())
//                    return;
                
                clickEvent(view);
                
                break;
            case R.id.tab_gallery:
            case R.id.tab_sms:
            case R.id.tab_map:
            case R.id.tab_memo:
                selectedTabButton(view);
                break;
            default:
                break;
        }
    }

    private void clickEvent(View view) {
        for (int i=0; i<mMonthTabs.length; i++) {
            mMonthTabs[i].setBackgroundColor(Color.WHITE);
        }
        
        setDay(0);
        
        if (view != null) {
            setMonth((Integer)view.getTag());
            view.setBackgroundColor(Color.DKGRAY);
        }
        
        Fragment currentFragment = mTabsAdapter.getItem(mViewPager.getCurrentItem());
        setExistDay(((BaseFragment) currentFragment).getExistDays(getYear(), getMonth()));
        
        for (int i=0; i<mTabsAdapter.getCount(); i++) {
            ((BaseFragment)mTabsAdapter.getItem(i)).onInit();
        }
    }
    
    /**
     * 탭을 선택 하였을 경우에 탭 이동하고 버튼 Selected 하도록 한다.
     * @param v
     */
    private void selectedTabButton(View v){

        if(mMenuTabs == null){
            LogUtil.e("mCloudTabs isn null");
            return;
        }

        try {            
            for(int i=0;i<mMenuTabs.length;i++){
                if(mMenuTabs[i].getId() == v.getId()){
                    mMenuTabs[i].setSelected(true);
                    mViewPager.setCurrentItem(i);
                }else{
                    mMenuTabs[i].setSelected(false);
                }                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void showSelectYearDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        dialog.setTitle(getString(R.string.hello_world));
        dialog.setSingleChoiceItems(strYearItems, selectedYearNo, new android.content.DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectedYearNo = which;
                tvYear.setText(strYearItems[which]);
                dialog.dismiss();
                
                setYear(Integer.valueOf(strYearItems[which]));
                clickEvent(mMonthTabs[getMonth()-1]);
            }
        }).show();
    }
    
    @Override
    public void onBackPressed() {
        
        if(isFinishing()){
            return;
        }
        
        if(mIsAppExit) {
            finish();
        } else {
            Toast.makeText(this, getResources().getString(R.string.app_is_exit_msg), Toast.LENGTH_SHORT).show();
            mIsAppExit = true;
            mExitHandler.sendEmptyMessageDelayed(0, 3000);
        }
    }
    
    private Handler mExitHandler = new Handler() {
        public void handleMessage(Message m) {
            mIsAppExit = false;
        }
    };
}
